package client.ui.view.dialogview;

import client.UserState;
import client.assets.Icons;
import client.control.Controller;
import client.control.ResponseEntity;
import client.entity.Record;
import client.ui.component.button.MaterialButton;
import client.ui.component.edittext.TextEdit;
import client.ui.theme.ThisFont;
import client.ui.util.MaterialColors;
import com.alibaba.fastjson.JSONObject;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class RecordDialog {
    public static void recordDialog(Frame owner, Container parentContainer){
        Executor singleThreadExecutor = Executors.newSingleThreadExecutor();
        JDialog dialog = new JDialog(owner,true);
        dialog.setSize(350,180);
        dialog.setResizable(false);
        dialog.setLocationRelativeTo(parentContainer);
        dialog.setTitle("我的售货记录");
        dialog.setIconImage(Icons.auction.getImage());

        JButton confirm = MaterialButton.BlueButton("确认",null);
        TextEdit startTime = new TextEdit("请输入统计开始时间(yyyy-MM-dd)");
        startTime.setText("2000-01-01");
        TextEdit endTime = new TextEdit("请输入统计截止时间(yyyy-MM-dd)");
        endTime.setText("2100-12-31");

        confirm.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date start;
                Date end;
                double price;
                //格式化并判断数据合法性
                try{
                    start = format.parse(startTime.getText());
                } catch (ParseException ex) {
                    startTime.setErrorText("请检查日期格式(yyyy-MM-dd)");
                    return;
                }
                try{
                    end = format.parse(endTime.getText());
                } catch (ParseException ex) {
                    endTime.setErrorText("请检查日期格式(yyyy-MM-dd)");
                    return;
                }
                if (start.getTime() > end.getTime()){
                    endTime.setErrorText("查询结束时间不能早于起始时间");
                    return;
                }

                //置空错误
                startTime.setErrorText("");
                endTime.setErrorText("");

                singleThreadExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        ResponseEntity responseEntity = Controller.RECORD_CONTROL.getRecordOfStore(UserState.getToken(),
                                startTime.getText(),
                                endTime.getText()
                        );
                        if (responseEntity.getCode() == 0){
                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    List<Record> records = JSONObject.parseArray(responseEntity.getData(), Record.class);
                                    showRecordCard(owner, parentContainer, records);
                                }
                            });
                        } else {
                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    JOptionPane.showMessageDialog(owner,"获取失败，这段时间您没有收入记录");
                                }
                            });
                        }
                    }
                });
            }
        });

        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        Box vBox = Box.createVerticalBox();
        vBox.add(startTime);
        vBox.add(endTime);
        vBox.add(new JLabel(" "));


        panel.add(vBox);
        panel.add(confirm);
        dialog.setContentPane(panel);

        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
    }

    private static void showRecordCard(Frame owner, Container parentContainer, List<Record> records){
        JDialog dialog = new JDialog(owner, true);
        dialog.setLocationRelativeTo(parentContainer);
        dialog.setTitle("我的售货记录");
        dialog.setIconImage(Icons.auction.getImage());
        double allPrice = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Object[] columnNames = {"交易Id","购买者Id","用户名", "购买数量", "单价", "购买时间", "合计"};
        Object[][] rowData = new Object[records.size()][];
        for (int i = 0; i < records.size(); i++) {
            Record r = records.get(i);
            rowData[i] = new Object[]{r.getRecordId(), r.getUserId(), r.getUserName(),r.getCount(),
                    r.getAmount() / r.getCount(), simpleDateFormat.format(r.getBoughtTime()),r.getAmount()
            };
            allPrice += r.getAmount();
        }
        JTable table = new JTable(rowData, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(750,300));
        table.getTableHeader().setFont(ThisFont.MIDDLE_BOLD_FONT);
        table.setFont(ThisFont.MIDDLE_FONT);
        table.setRowHeight(40);
        table.getTableHeader().setForeground(MaterialColors.COSMO_RED);
        JPanel panel = new JPanel(new BorderLayout());

        JScrollPane scrollPane = new JScrollPane(table);
        JLabel label = new JLabel("合计:" + allPrice, SwingConstants.RIGHT);
        label.setForeground(MaterialColors.COSMO_BLUE);
        label.setBorder(new EmptyBorder(12,12,12,12));
        label.setFont(ThisFont.BIG_BOLD_FONT);

        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(label, BorderLayout.SOUTH);

        dialog.setContentPane(panel);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setSize(750,350);
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenSize = toolkit.getScreenSize();
        dialog.setLocation(screenSize.width / 2 - 375, screenSize.height / 2 - 150);
        dialog.setVisible(true);
    }
}
